package com.example.demo1.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.demo1.util.JWTUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MyHttpInterceptor extends HandlerInterceptorAdapter {

    private static final void handleError(String ErrorMsg, HttpServletResponse response) throws IOException {
        response.setStatus(403);
        log.error("权限错误 ：" + ErrorMsg);
        PrintWriter out = response.getWriter();
        out.write(ErrorMsg);
        out.flush();
        out.close();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        response.setCharacterEncoding("UTF-8");

        String token = request.getHeader("token");

        if (token == null || StringUtils.isEmpty(token)) {
            handleError("未登录", response);
            return false;
        }

        Claims claims = null;
        try {
            claims = JWTUtil.getJwsClaims(token);
        } catch (Exception e) {
            handleError("token 无效", response);
            return false;
        }

        Date time = claims.getExpiration();
        if (time.before(new Date())) {
            handleError("token 已过期，请重新登录", response);
            return false;
        }

        System.out.println(request.getRequestURL().toString());
        return true;
    }

}
